package service

import (
	"encoding/json"
	"strings"

	"lucidity.note/app/common/bean"
	"lucidity.note/app/common/db"
)

type UserSettingService struct{}

// 获取外观设置
func (*UserSettingService) GetAppearanceConfigService() *bean.AppearanceConfig {
	return GetAppearanceConfig()
}

func (*UserSettingService) UpdateAppearanceSettingService(appearance *bean.AppearanceConfig) error {
	// 数据入库
	dbConn := db.GetDiskInxNustDB()
	appearance.DefaultBkDataSet = GetAppearanceConfig().DefaultBkDataSet
	appearance.EditorThemeDataSet = GetAppearanceConfig().EditorThemeDataSet

	jsonBys, _ := json.Marshal(&appearance)
	if err := dbConn.Insert(bean.GetNustDBBucketOfUserSet(), bean.GetNustDBKeyOfAppearanceSetting(), string(jsonBys)); nil != err {
		return err
	}

	// 更新全局配置
	SetAppearanceConfig(appearance)
	return nil
}

// 获取 Git 同步设置
func (*UserSettingService) GetGitSyncSettingConfigService() *bean.GitSyncConfig {
	return GetGitSyncConf()
}

// 更新 Git 同步设置
func (*UserSettingService) UpdateGitSyncSettingService(config *bean.GitSyncConfig) error {
	// 数据入库
	dbConn := db.GetDiskInxNustDB()
	jsoBys, _ := json.Marshal(&config)
	if err := dbConn.Insert(bean.GetNustDBBucketOfUserSet(), bean.GetNustDBKeyOfGitSyncSetting(), string(jsoBys)); nil != err {
		return err
	}

	// 更新全局变量
	SetGitSyncConf(config)
	return nil
}

func (*UserSettingService) GetConfResourceFileInfoService() *bean.AppReourceInfo {
	appearanceConfig := GetAppearanceConfig()

	var bkImageUrl = ""
	if strings.EqualFold(appearanceConfig.AppBKMode, "default") {
		bkImageUrl = appearanceConfig.DefaultBK
	} else {
		bkImageUrl = appearanceConfig.CustomBk
	}

	return &bean.AppReourceInfo{
		AppTheme:    appearanceConfig.AppTheme,
		EditorTheme: appearanceConfig.EditorTheme,
		BKImage:     bkImageUrl,
	}
}

func (*UserSettingService) GetNoteTextConfService() []*bean.NoteTextConf {
	return GetNoteTextConf()
}

func (*UserSettingService) UpdateNoteTextConfService(config *bean.NoteTextConf) error {
	// 数据入库
	dbConn := db.GetDiskInxNustDB()
	noteTextConfs := GetNoteTextConf()

	// 将值进行替换更新
	for _, item := range noteTextConfs {
		if strings.EqualFold(item.Name, config.Name) {
			item.Enable = !config.Enable
			break
		}
	}

	jsoBys, _ := json.Marshal(&noteTextConfs)
	if err := dbConn.Insert(bean.GetNustDBBucketOfUserSet(), bean.GetNustDBKeyOfNoteTextConf(), string(jsoBys)); nil != err {
		return err
	}

	// 更新全局变量
	SetNoteTextConf(noteTextConfs)
	return nil
}
